package cn.zkw.action.filter;

import cn.zkw.service.VisitorVolumeService;
import cn.zkw.vo.VisitorVolume;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleCORSFilter implements Filter {
    private boolean isCross = false;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat();

    @Autowired
    private VisitorVolumeService visitorVolumeService;

    @Override
    public void destroy() {
        isCross = false;
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if(httpServletRequest.getSession().isNew()){
            //创建一个visitorvolume，里面只有日期信息
            VisitorVolume visitorVolume = new VisitorVolume();
            visitorVolume.setDay(new Date());
            if(visitorVolumeService.selectCurrent(simpleDateFormat.format(new Date()))==null){  //查询当日访问量信息
                visitorVolumeService.insertInit(visitorVolume);       //初始化当日访问量为1
            }else{
                visitorVolumeService.updateVolume(visitorVolume);  //访问量+1
            }
            System.out.println("新的请求");
        }
        if (isCross) {
            System.out.println("拦截请求: " + httpServletRequest.getServletPath());
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Max-Age", "0");
            httpServletResponse.setHeader("Access-Control-Allow-Headers",
                    "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("XDomainRequestAllowed", "1");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String isCrossStr = filterConfig.getInitParameter("IsCross");
        isCross = isCrossStr.equals("true") ? true : false;
        System.out.println(isCrossStr);
    }

}